package com.gitee.huanminabc.ddd.config;

import com.gitee.huanminabc.utils_tools.web_base.utils.WebContextUtil;
import feign.RequestInterceptor;
import feign.RequestTemplate;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.util.Enumeration;

/**
 * @author huanmin
 * @date 2024/2/28
 */
@Component
public class FeignHeaderConfig  implements RequestInterceptor {
    @Override
    public void apply(RequestTemplate template) {
        ServletRequestAttributes attributes = (ServletRequestAttributes) WebContextUtil.getRequest();
        if(attributes!=null){
            HttpServletRequest request = attributes.getRequest();
            Enumeration<String> headerNames = request.getHeaderNames();
            if (headerNames != null) {
                while (headerNames.hasMoreElements()) {
                    String name = headerNames.nextElement();
                    String values = request.getHeader(name);
                    if("Authorization".equals(name)){//添加Authorization
                        template.header(name, values);
                    }
                }
            }
        }else{
            //如果是内部调用，没有web上下文，那么就手动获取/user/createMockToken,这里先不处理,以后在完善

        }
    }
}
